package com.elitesland.core.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.val;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.time.LocalDateTime;

/**
 * @author Mir
 * @date 2018-11-08
 */
public final class HttpServletResponseUtil {

    private static String UTF8 = "UTF-8";
    private static String CONTENT_TYPE = "application/json";

    private HttpServletResponseUtil() {
        throw new AssertionError();
    }

    public static void printJSON(HttpServletResponse response, Object object) throws Exception {
        val mapper = new ObjectMapper();
        val javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class, SpringContextHolder.getBean(LocalDateTimeSerializer.class));
        javaTimeModule.addDeserializer(LocalDateTime.class, SpringContextHolder.getBean(LocalDateTimeDeserializer.class));
        mapper.registerModule(javaTimeModule);

        response.setCharacterEncoding(UTF8);
        response.setContentType(CONTENT_TYPE);
        PrintWriter printWriter = response.getWriter();
        printWriter.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object));
        printWriter.flush();
        printWriter.close();
    }
}
